package com.sgb.member.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.SparseArray;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;

import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;

import com.google.android.material.tabs.TabLayout;
import com.sgb.member.MemberConfig;
import com.sgb.member.R;
import com.sgb.member.databinding.ActivityMemberManageBinding;
import com.sgb.member.di.DaggerMemberComponent;
import com.sgb.member.di.MemberModule;
import com.sgb.member.entity.MemberBean;
import com.sgb.member.event.EventConstant;
import com.sgb.member.event.MemberEvent;
import com.sgb.member.ui.fragment.MemberTypeDemandFragment;
import com.sgb.member.ui.fragment.PersonTypeDemandFragment;
import com.sgb.member.ui.fragment.MemberTypeFragment;
import com.sgb.member.view_model.MemberManageModel;
import com.swgk.core.base.AppActivity;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.customview.XCustomTabLayout;
import com.swgk.core.recyclerview.adapter.SlidingFragmentPagerAdapter;
import com.swgk.core.util.MToast;
import com.swgk.core.view.selection.CommonPopEntity;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;

import javax.inject.Inject;

public class MemberManageActivity extends AppActivity {

    @Inject
    MemberManageModel mModel;
    private ActivityMemberManageBinding mBinding;
    private final SparseArray<String> mSearchList = new SparseArray<>();

    private ArrayList<Fragment> mFragments;

    private int comType;

    public static void start(Context context) {
        start(context, 0);
    }

    public static void start(Context context, int index) {
        start(context, index, false, false);
    }

    public static void start(Context context, int index, boolean isJumpFromUserCenter) {
        start(context, index, isJumpFromUserCenter, false);
    }

    public static void start(Context context, int index, boolean isJumpFromUserCenter, boolean isSingle) {
        Intent intent = new Intent(context, MemberManageActivity.class);
        intent.putExtra("jumpIndex", index);
        intent.putExtra("jumpFrom", isJumpFromUserCenter);
        intent.putExtra("jumpSingle", isSingle);
        context.startActivity(intent);
    }

    public static void start(Context context, int cateType, CommonPopEntity entity) {
        Intent intent = new Intent(context, MemberManageActivity.class);
        intent.putExtra("cateType", cateType);
        intent.putExtra("jumpObject", entity);
        context.startActivity(intent);
    }

    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
        DaggerMemberComponent.builder()
                .appComponent(appComponent)
                .memberModule(new MemberModule(this))
                .build()
                .inject(this);
    }

    @Override
    protected void initView() {
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_member_manage);
        initSearchView();
        int cateType = getIntent().getIntExtra("cateType", -1);
        boolean isJumpFromUserCenter = getIntent().getBooleanExtra("jumpFrom", false);
        boolean isJumpSingle = getIntent().getBooleanExtra("jumpSingle", false);//是否单独显示
        int index = getIntent().getIntExtra("jumpIndex", 0); // 需方会员 0; 供方会员 1
        CommonPopEntity popEntity = (CommonPopEntity) getIntent().getSerializableExtra("jumpObject");
        mFragments = new ArrayList<>();
        // 类型 0个人 1企业 2团队
        comType = MemberConfig.getInstance().getComType();
        String[] mTitles;
        if (isJumpSingle) {
            mTitles = new String[1];
            mTitles[0] = index == 0 ? "需方会员" : "供方会员";
            mBinding.tabLayout.setVisibility(View.GONE);
            if (comType == MemberConfig.WEBSITE_FOR_PERSONAL) {
                mFragments.add(PersonTypeDemandFragment.newInstance(index, cateType, popEntity));
            } else {
                mFragments.add(MemberTypeDemandFragment.newInstance(index, cateType, popEntity));
            }
            SlidingFragmentPagerAdapter mPagerAdapter = new SlidingFragmentPagerAdapter(getSupportFragmentManager(), mFragments, mTitles);
            mBinding.vp.setOffscreenPageLimit(mTitles.length);
            mBinding.vp.setAdapter(mPagerAdapter);
        } else {
            if (comType == MemberConfig.WEBSITE_FOR_PERSONAL) {
                mTitles = new String[]{"需方会员", "供方会员"};
                mFragments.add(PersonTypeDemandFragment.newInstance(0, cateType, popEntity));
                mFragments.add(PersonTypeDemandFragment.newInstance(1, cateType, popEntity));
            } else {
                if (isJumpFromUserCenter) {
                    mTitles = new String[]{"需方会员", "供方会员"};
                    mFragments.add(MemberTypeDemandFragment.newInstance(0, cateType, popEntity));
                    mFragments.add(MemberTypeDemandFragment.newInstance(1, cateType, popEntity));
                } else {
                    mTitles = new String[]{"需方会员", "供方会员", "企业关注会员", "关注企业会员"};
                    mFragments.add(MemberTypeDemandFragment.newInstance(0, cateType, popEntity));
                    mFragments.add(MemberTypeDemandFragment.newInstance(1, cateType, popEntity));
                    mFragments.add(MemberTypeFragment.newInstance(2, cateType, popEntity));
                    mFragments.add(MemberTypeFragment.newInstance(3, cateType, popEntity));
                }
            }
            if (mTitles.length > 3) {
                mBinding.tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
            } else {
                mBinding.tabLayout.setTabMode(TabLayout.MODE_FIXED);
            }
            SlidingFragmentPagerAdapter mPagerAdapter = new SlidingFragmentPagerAdapter(getSupportFragmentManager(), mFragments, mTitles);
            mBinding.vp.setOffscreenPageLimit(mTitles.length);
            mBinding.vp.setAdapter(mPagerAdapter);
            mBinding.tabLayout.setupWithViewPager(mBinding.vp);
            mBinding.tabLayout.setNormalColor(R.color.color_main_bg);
            mBinding.tabLayout.setSelectColor(R.color.color_white);
            mBinding.tabLayout.setNormalSize(16);
            mBinding.tabLayout.setSelectSize(18);
            mBinding.tabLayout.addOnTabSelectedListener(mTitles, new XCustomTabLayout.SimpleSelectedListener() {
                @Override
                public void onTabSelected(TabLayout.Tab tab) {
                    String s = mSearchList.get(tab.getPosition());
                    mBinding.activityBar.etView.setText(s);
                    mBinding.vp.setCurrentItem(tab.getPosition());
                }
            });

            if (index < mFragments.size()) {
                mBinding.vp.setCurrentItem(index);
            }
        }
    }

    private String mSearchText = ""; // 搜索内容

    private void initSearchView() {
        mBinding.activityBar.ivBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onBackPressed();
            }
        });
        mBinding.activityBar.etView.setImeOptions(EditorInfo.IME_ACTION_SEARCH);
        mBinding.activityBar.etView.setHint("请输入企业名称");
        mBinding.activityBar.etView.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) {
                    if (TextUtils.isEmpty(mBinding.activityBar.etView.getText().toString())) {
                        MToast.showToast(getActivity(), "请输入企业名称");
                        return true;
                    }
                    if (mSearchText.equals(mBinding.activityBar.etView.getText().toString())) {
                        MToast.showToast(getActivity(), "请输入不同的搜索内容");
                        return true;
                    }
                    mSearchText = mBinding.activityBar.etView.getText().toString().trim();
                    loadSearchData();
                }
                return false;
            }
        });
        mBinding.activityBar.etView.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (TextUtils.isEmpty(s) || s.length() == 0) {
                    mBinding.activityBar.tvSearchDelete.setVisibility(View.INVISIBLE);
                } else {
                    mBinding.activityBar.tvSearchDelete.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        mBinding.activityBar.tvSearchDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mSearchText = "";
                mBinding.activityBar.etView.setText("");
                loadSearchData();
            }
        });
        mBinding.activityBar.tvSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(mSearchText)) {
                    if (TextUtils.isEmpty(mBinding.activityBar.etView.getText().toString())) {
                        MToast.showToast(getActivity(), "请输入企业名称");
                        return;
                    }
                }
                if (mSearchText.equals(mBinding.activityBar.etView.getText().toString())) {
                    MToast.showToast(getActivity(), "请输入不同的搜索内容");
                    return;
                }
                mSearchText = mBinding.activityBar.etView.getText().toString().trim();
                loadSearchData();
            }
        });
        mBinding.activityBar.tvSearchDelete.setVisibility(View.INVISIBLE);
    }

    public String getSearchText() {
        int tabPosition = mBinding.vp.getCurrentItem();
        return mSearchList.get(tabPosition);
    }

    private void loadSearchData() {
        int tabPosition = mBinding.vp.getCurrentItem();
        mSearchList.put(tabPosition, mSearchText);
        Fragment fragment = mFragments.get(tabPosition);
        if (comType == MemberConfig.WEBSITE_FOR_PERSONAL) {
            if (fragment instanceof PersonTypeDemandFragment) {
                ((PersonTypeDemandFragment) fragment).loadData(false);
            }
        } else {
            if (fragment instanceof MemberTypeDemandFragment) {
                ((MemberTypeDemandFragment) fragment).loadData(false);
            } else if (fragment instanceof MemberTypeFragment) {
                ((MemberTypeFragment) fragment).loadData(false);
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onEvent(MemberEvent event) {
        Fragment fragment = mFragments.get(mBinding.vp.getCurrentItem());
        if (fragment instanceof MemberTypeDemandFragment) {
            MemberTypeDemandFragment typeDemandFragment = (MemberTypeDemandFragment) mFragments.get(mBinding.vp.getCurrentItem());
            if (event.getMessageTag() == EventConstant.EVENT_MEMBER_UPDATE_LEVEL) {
                MemberBean bean = (MemberBean) event.getMessageData();
                int pos = event.getPos();
                if (pos > -1) {
                    typeDemandFragment.updateMemberLevel(pos, bean);
                }
            }
        }
        EventBus.getDefault().removeStickyEvent(event);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        int currentItem = mBinding.vp.getCurrentItem();
        Fragment fragment = mFragments.get(currentItem);
        if (fragment instanceof MemberTypeDemandFragment) {
            fragment.onActivityResult(requestCode, resultCode, data);
        } else if (fragment instanceof PersonTypeDemandFragment) {
            fragment.onActivityResult(requestCode, resultCode, data);
        }
    }
}
